package com.hdu.utils;

import com.hdu.InvocationHandler;

import javax.tools.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.util.Arrays;


public class JavaCompilerUtils {
    public static Object getObject(String absoluteClassPath, String relativeClassPath, ClassLoader loader, InvocationHandler h) throws MalformedURLException, ClassNotFoundException {
        File sourceFile = new File(absoluteClassPath);
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
        boolean success = task.call();
        if (!success) {
            System.err.println("Compilation failed.");
            return null;
        }
        try {
            Class<?> myClass = loader.loadClass(relativeClassPath);
            return myClass.getDeclaredConstructor(InvocationHandler.class).newInstance(h);
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException |
                 NoSuchMethodException e) {
            Class<?> myClass = loader.loadClass(relativeClassPath);
            try {
                return myClass.getDeclaredConstructor(InvocationHandler.class).newInstance(h);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                     NoSuchMethodException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
